package com.javasm.interceptors;

import com.javasm.service.RedisService;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component(value = "MyLoginInterceptor")
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private RedisService redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
//        String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
//        // 如果不是映射到方法直接通过
//        if (!(object instanceof HandlerMethod)) {
//            return true;
//        }
//        HandlerMethod handlerMethod = (HandlerMethod) object;
//        Method method = handlerMethod.getMethod();
//        //检查是否有passtoken注释，有则跳过认证
//        if (method.isAnnotationPresent(PassToken.class)) {
//            PassToken passToken = method.getAnnotation(PassToken.class);
//            if (passToken.required()) {
//                return true;
//            }
//        }
//        if (token == null) {
//            throw new RuntimeException("无token，请重新登录");
//        }
//        String userId;
//        try {
//            userId = JWT.decode(token).getAudience().get(0);
//        } catch (JWTDecodeException j) {
//            throw new Exception("token无效");
//        }
//        User user = null;
//        String key = RedisPreEnum.JWT_TOKEN_PRE.getPre() + userId + IpUtils.getIpAddr(httpServletRequest);
//        if (redisUtil.hasKey(key)) {
//            Object o = redisUtil.get(key);
//            user = JSONObject.toJavaObject((JSON) JSON.toJSON(o), User.class);
//        }
//        if (user == null) {
//            throw new RuntimeException("请重新登录");
//        }
//        // 验证 token
//        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getUserPassword())).build();
//        try {
//            jwtVerifier.verify(token);
//        } catch (Exception e) {
//            throw new Exception("token无效");
//        }
        return true;
    }


}

